package fr.enseirb.mycub.activity.component.layer;

import java.util.ArrayList;

import android.database.Cursor;
import android.os.AsyncTask;
import fr.enseirb.mycub.R;
import fr.enseirb.mycub.component.map.OverlayBundleItem;

public abstract class PopulateOverlays extends AsyncTask<Void, Integer, Void> {

	private ArrayList<? extends OverlayBundleItem> mOverlays = null;
	private Layer layer;
	private boolean mUpdateOnPostExecute = false;
	private int OK = 0;
	private int CANCELLED = -1;
	private int EMPTY = -2;

	public PopulateOverlays(Layer layer){
		this.layer = layer;
	}

	@Override
	protected Void doInBackground(Void... unused) {
		publishProgress(getStationsCursor());
		return null;
	}

	protected abstract int getOverlayCount();
	protected abstract ArrayList<Cursor> getOverlayCursor();
	protected abstract ArrayList<? extends OverlayBundleItem> getOverlayFromCursor(ArrayList<Cursor> cursor);

	private int getStationsCursor() {
		if (getOverlayCount() == 0) {
			return EMPTY;
		}
		if (isCancelled())
			return CANCELLED;
		ArrayList<Cursor> cursor = getOverlayCursor();
		if (isCancelled()) {
			for(Cursor singleCursor : cursor)
				singleCursor.close();
			return CANCELLED;
		}
		mOverlays = getOverlayFromCursor(cursor);
		for(Cursor singleCursor : cursor)
			singleCursor.close();
		return OK;
	}

	@Override
	protected void onPreExecute() {
		layer.activity.showProgressDialog(layer.activity.getString(R.string.loading),
				layer.activity.getString(R.string.showing_load));
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		if (values[0] == CANCELLED) {
			return;
		} else if (mOverlays != null) {
			layer.mStationsOverlay.setItems(mOverlays);
			layer.mMapView.invalidate();
		} else {
		}
	}

	@Override
	protected void onPostExecute(Void unused) {
		layer.activity.dismissProgressDialog();
		layer.mPopulateOverlays = null;
		if (mUpdateOnPostExecute) {
			layer.executeUpdateOverlays();
		}
	}

	@Override
	protected void onCancelled() {
		layer.activity.dismissProgressDialog();
		super.onCancelled();
	}

	public void setUpdateOnPostExecute() {
		mUpdateOnPostExecute = true;
	}
}